package com.hwl.trade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.hwl.commonutils.utils.AssertUtil;
import com.hwl.servicebase.dto.CourseDto;
import com.hwl.servicebase.dto.MemberDto;
import com.hwl.trade.feign.CenterMemberService;
import com.hwl.trade.feign.EduCourseService;
import com.hwl.trade.mapper.OrderMapper;
import com.hwl.trade.mapper.PayLogMapper;
import com.hwl.trade.pojo.Order;
import com.hwl.trade.pojo.PayLog;
import com.hwl.trade.service.OrderService;
import com.hwl.trade.util.OrderNoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author long
 * @since 2021-10-08
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private EduCourseService eduCourseService;
    @Resource
    private CenterMemberService centerMemberService;
    @Resource
    private PayLogMapper payLogMapper;

    @Override
    public String saveOrder(String courseId, String memberId) {
        //查询当前用户是否已有当前课程的订单
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>()
                .eq("course_id", courseId).eq("member_id", memberId);
        Order orderExist = baseMapper.selectOne(wrapper);
        if (orderExist != null) {
            return orderExist.getId(); //如果订单已存在，则直接返回订单id
        }

        //查询课程信息
        CourseDto courseDto = eduCourseService.getCourseDtoById(courseId);
        AssertUtil.isTrue(courseDto == null, "获取课程信息时出错！");
        //查询用户信息
        MemberDto memberDto = centerMemberService.getMemberDtoById(memberId);
        AssertUtil.isTrue(memberDto == null, "查询用户信息时出错！");

        //创建订单
        Order order = new Order()
                .setOrderNo(OrderNoUtils.getOrderNo()).setCourseId(courseId)
                .setCourseTitle(courseDto.getTitle())
                .setCourseCover(courseDto.getCover())
                .setTeacherName(courseDto.getTeacherName())
                .setTotalFee(courseDto.getPrice().multiply(new BigDecimal(100))) //单位：分
                .setMemberId(memberId)
                .setMobile(memberDto.getMobile())
                .setNickname(memberDto.getNickname())
                .setStatus(0) //未支付
                .setPayType(1); //微信支付

        log.info(baseMapper.insert(order) > 0 ? "新增订单成功！" : "新增订单失败！");
        return order.getId();
    }

    @Override
    public Order getOrderById(String orderId, String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>()
                .eq("id", orderId).eq("member_id", memberId);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public Boolean isBuyByCourseId(String courseId, String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>()
                .eq("course_id", courseId).eq("member_id", memberId)
                .eq("status", 1);
        return baseMapper.selectCount(wrapper) > 0;
    }

    @Override
    public List<Order> selectByMemberId(String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>()
                .orderByDesc("gmt_create").eq("member_id", memberId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public boolean removeById(String orderId, String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>()
                .eq("id", orderId).eq("member_id", memberId);
        return this.remove(wrapper);
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        return baseMapper.selectOne(new QueryWrapper<Order>().eq("order_no", orderNo));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrderStatus(Map<String, String> notifyMap) {

        //更新订单状态
        String outTradeNo = notifyMap.get("out_trade_no");
        Order order = this.getOrderByOrderNo(outTradeNo);
        if (order.getStatus() == 0) {
            order.setStatus(1);//支付成功
            log.info(baseMapper.updateById(order) > 0 ? "订单更新成功！" : "订单更新失败！");

            //记录支付日志
            PayLog payLog = new PayLog()
                    .setOrderNo(outTradeNo)
                    .setPayTime(new Date())
                    .setPayType(1) //支付类型：微信支付
                    .setTotalFee(Long.parseLong(notifyMap.get("total_fee")))
                    .setTradeState(notifyMap.get("result_code"))
                    .setTransactionId(notifyMap.get("transaction_id"))
                    .setAttr(new Gson().toJson(notifyMap));
            log.info(payLogMapper.insert(payLog) > 0 ? "支付日志记录成功！" : "支付日志记录失败！");

            //更新课程销量
            eduCourseService.updateBuyCountById(order.getCourseId());
        }
    }

    @Override
    public boolean queryOrderStatus(String orderNo) {
        Order order = baseMapper.selectOne(new QueryWrapper<Order>().eq("order_no", orderNo));
        return order.getStatus() == 1;
    }
}
